package com.ineatconseil.yougo.pages.requesttypes.view;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;

import com.ineatconseil.yougo.beans.ActionType;
import com.ineatconseil.yougo.beans.RequestType;
import com.ineatconseil.yougo.dto.RequestTypeDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.pages.AbstractPage;
import com.ineatconseil.yougo.pages.requesttypes.list.RequestTypesList;
import com.ineatconseil.yougo.services.rest.RestPath;

public class RequestTypeView extends AbstractPage {

	@Property
	private RequestType requestType;

	@Property
	@Persist(PersistenceConstants.SESSION)
	private long requestTypeId;

	@Component(id = "formRequestType")
	private BeanEditForm _form;

	@InjectPage
	private RequestTypesList typesList;

	/**
	 * Load action.
	 */
	@Log
	void onActivate(long requestTypeId) {

		try {

			if (!isEmptyParameter(String.valueOf(requestTypeId))) {

				requestType =
						this.getMapper().map(
								this.getRestServiceInvoker().call(
										RestPath.getSimplePath(RestPath.PATH_REQUEST_TYPES, String
												.valueOf(requestTypeId)), RequestTypeDto.class), RequestType.class);
				this.requestTypeId = requestTypeId;
			} else {
				requestType = new RequestType();
				this.requestTypeId = 0;
			}

		} catch (RestServiceException e) {
			_form.recordError(getRESTErrorMessage(e.getStatus()));
		}

	}

	/**
	 * Submit action.
	 */
	@Log
	Object onSuccess() {

		try {

			if (this.requestTypeId != 0) {

				// Update
				this.requestType.setId(this.requestTypeId);
				this.getRestServiceInvoker().update(
						RestPath.getSimplePath(RestPath.PATH_REQUEST_TYPES, String.valueOf(requestTypeId)),
						getMapper().map(requestType, RequestTypeDto.class), RequestTypeDto.class);

				typesList.setActionMessageOk("requesttype", ActionType.UPDATE);

			} else {

				// Create
				this.requestType.setId(null);
				this.getRestServiceInvoker().save(RestPath.getSimplePath(RestPath.PATH_REQUEST_TYPES, ""),
						getMapper().map(requestType, RequestTypeDto.class), RequestTypeDto.class);

				typesList.setActionMessageOk("requesttype", ActionType.CREATE);

			}

			return typesList;

		} catch (RestServiceException e) {
			_form.recordError(getRESTErrorMessage(e.getStatus()));
			return null;
		}

	}

}
